package index;

import fileoperation.FileCreation;
import gitobject.Blob;
import gitobject.Tree;
import repository.Repository;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class Index {
    public static LinkedList<String[]> indexList = new LinkedList<>();  //存储索引信息
    protected static File indexFile = new File(Repository.getGitDir() + File.separator + "index");//暂存区文件

    public Index() {
    }

    public static File getIndexFile() {
        return indexFile;
    }

    public static LinkedList<String[]> getAddList() {
        return indexList;
    }

    public static boolean inIndexList(String filepath) throws IOException {
        boolean fileExist = false;
//        LinkedList<String[]> list = readList();
        if(!indexList.isEmpty()){
            for (String[] record : indexList) {
                if (record[3].equals(filepath)) {
                    fileExist = true;
                    break;
                }
            }
        }
        return fileExist;
    }

    public static void addIndexRecord(String filepath) throws Exception {
        File file = new File(Repository.getWorkTree() + File.separator + filepath);
        long lastmodified = file.lastModified();//获取文件最后修改时间
        Date date = new Date(lastmodified);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//将Date转化为String，便于存储
        String modifytime = df.format(date);

        List<String> pathList = Arrays.asList(filepath.split("\\\\"));//按照斜杠分割文件路径得到文件名
        String filename = pathList.get(pathList.size() - 1);
        String[] noteArray = new String[5];//每条记录都包括Key-Value-Object类型编号，暂存文件hash值，文件名，修改时间

        if (file.isFile()) {
            Blob blob = new Blob(file);//创建blob对象，并将hash文件存入objects文件夹

            noteArray[0] = blob.getMode();
            noteArray[1] = blob.getKey();
            noteArray[2] = filename;
            noteArray[3] = filepath;
            noteArray[4] = modifytime;
            indexList.add(noteArray);

            String note = blob.getMode() + "  " + blob.getKey() + "  " + filename + "  " + filepath + "  " + modifytime + "\n";

            FileWriter fileWriter = new FileWriter(indexFile, true);//在保留文件原有内容的基础上写入新的内容
            fileWriter.write(note);
            fileWriter.close();
        }

        if (file.isDirectory()) {
            Tree tree = new Tree(file);//创建tree对象，并将hash文件存入objects文件夹

            noteArray[0] = tree.getMode();
            noteArray[1] = tree.getKey();
            noteArray[2] = filename;
            noteArray[3] = filepath;
            noteArray[4] = modifytime;
            indexList.add(noteArray);

            String note = tree.getMode() + "  " + tree.getKey() + "  " + filename + "  " + filepath + "  " + modifytime + "\n";
            FileWriter fileWriter = new FileWriter(indexFile, true);//在保留文件原有内容的基础上写入新的内容
            fileWriter.write(note);
            fileWriter.close();
            File[] fs = file.listFiles();
            for(int i=0; i<fs.length; i++){
                addIndexRecord(filepath + File.separator +fs[i].getName());//把文件夹中的文件信息加进indexList
            }
        }
    }

    public static void deleteIndexRecord(String filepath) throws IOException {
        Iterator<String[]> iterator = indexList.iterator();//用迭代器删除index链表中待删除文件记录
        while (iterator.hasNext()) {
            String[] record = iterator.next();
            if (record[3].equals(filepath)) {
                iterator.remove();
            }
        }

        ArrayList<String> list = new ArrayList<>(); //读取文件内容，将不包含待删除记录的文件内容存入列表
        String str;

        BufferedReader br = new BufferedReader(new FileReader(indexFile));//用BufferedReader按行读取
        while ((str = br.readLine()) != null) {
            if (str.contains(filepath)) {
                continue;//遇到待删除记录，跳过
            }
            list.add(str); //将除待删除的文件记录外的其他记录存入列表
        }
        br.close();

        BufferedWriter bw = new BufferedWriter(new FileWriter(indexFile));//将list中的记录重新写入index文件
        if (list.size() != 0) {
            for (String string : list) {
                bw.write(string);
                bw.newLine();
            }
        } else {
            bw.write(" ");
        }
        bw.flush();
        bw.close();
    }

//    public static void writeList() throws IOException {
//        File listFile = new File(Repository.getGitDir() + File.separator + "listRecord");
//        FileWriter fw = new FileWriter(listFile, true);
//        for(int i = 0; i < indexList.size(); i++){
//            String[] array = indexList.get(i);
//            fw.write(array.toString());
//        }
//        fw.close();
//    }
//
//    public static LinkedList<String[]> readList() throws IOException {
//        LinkedList<String[]> list = new LinkedList<>();
//        File listFile = new File(Repository.getGitDir() + File.separator + "listRecord");
//        if(listFile.exists()) {
//            FileInputStream fis = new FileInputStream(listFile);
//            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//            while (br.readLine() != null) {
//                String[] array = br.readLine().split(" ");
//                list.add(array);
//            }
//        }
//        return list;
//    }
}

